package com.yssoft.framework;

import com.yssoft.utils.AppUtil;
import org.apache.log4j.Logger;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 陈翼东
 * @说明  过滤判断app用户是否登陆，如果没登陆直接返回没有登陆的json数据
 * @time 2018/4/29 上午 09:07
 */
public class AppLoginFilter implements Filter {

    
    
    @Resource
    private static Logger logger=Logger.getLogger(AppLoginFilter.class);
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("AppLoginFilter过滤器被创建");
    }
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String servletPath = request.getServletPath();
        //为了实现app的session能够获取到在controller的上面添加跨域注解，过滤器中不控制跨域
        //response.setHeader("Access-Control-Allow-Origin", "*");

        //response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
       // response.setHeader("Access-Control-Max-Age", "3600");
        //response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
        //response.setHeader("Access-Control-Allow-Credentials", "true");
        List<String>  path=new ArrayList<>();//不希望过滤的添加到list中
        path.add("/app/resetPassword");
        path.add("/app/getVerificationCode");
        path.add("/app/login");
        path.add("/app/register/checkPhone");
        path.add("/app/register/getVerificationCode");
        path.add("/app/register/saveAccounts");
        path.add("/app/register/saveEnt");
        path.add("/app/register/uploadImage");
        path.add("/public/");
        ResponseWrapper wrapperResponse = new ResponseWrapper(response);//转换成代理类
        //兼容公众溯源接口
        Boolean isPub=false;
        if(servletPath.contains("/public/")) {
        	isPub=true;
        }
        //兼容放行公众溯源接口
        if(path.contains(servletPath) ||isPub ){
            //登陆，找回密码的直接通过
                 myWrite(filterChain,request,wrapperResponse,response);
        }else{
            HttpSession session = request.getSession();
            Object appUser = session.getAttribute("appUser");
               if(appUser!=null){
                //如果已经登陆则直接通过
                 myWrite(filterChain,request,wrapperResponse,response);
                 
            }else{
                PrintWriter writer = response.getWriter();
                Object result = AppUtil.returnMapJson("3", "您还没有登录请先登录!", null);
                writer.write(result.toString());
            }
        }
    }
    
    public void myWrite( FilterChain filterChain,HttpServletRequest request,ResponseWrapper wrapperResponse,HttpServletResponse response) throws IOException, ServletException {
        filterChain.doFilter(request, wrapperResponse);
        byte[] content = wrapperResponse.getContent();//获取返回值
        if (content.length > 0){
            String str = new String(content, "UTF-8");
            if(str.indexOf("files")>=0){
                //将图片地址替换成服务器地址加图片名称
                str=str.replaceAll("/files","http://" +request.getServerName() + ":"+request.getServerPort()+request.getContextPath()+"/files");
            }
            ServletOutputStream writer = response.getOutputStream();
            writer.write(str.getBytes("UTF-8"));
            writer.flush();
        }
    }
    
    
    @Override
    public void destroy() {
        logger.info("AppLoginFilter过滤器被销毁");
    }
    
}
